<?php defined("MAIN_DIR") or die("No direct access");

class Router {

	private $_path = array();
	private $_GET = array();
	private $_POST = array();

	function __construct() {
		$request = explode("?",$_SERVER['REQUEST_URI']);
		$dir = trim($request[0],"/");

		// get GET-params
		if (count($_GET)) {
			foreach($_GET as $key=>$value) {
				$this->_GET[$key] = $value;
			}
		}
		// get POST-params
		if (count($_POST)) {
			foreach($_POST as $key=>$value) {
				$this->_POST[$key] = $value;
			}
		}
		// get cookie
		if (count($_COOKIE)){
			foreach($_COOKIE as $key=>$value){
				$this->_COOKIE[$key] = $value;
			}
		}

		// ������ ����
		$mas = explode("/",$dir);
		for ($i = 0; $i < count($mas); $i++) {
			array_push($this->_path,$mas[$i]);
		}
	}

	public function getPath($number=1) {
		$number--;
		if (isset($this->_path[$number])){
			return $this->_path[$number];
		}
		return "";
	}

	public function GET($var){
		return isset($this->_GET[$var]) ? $this->_GET[$var] : null;
	}
	public function POST($var){
		return isset($this->_POST[$var]) ? $this->_POST[$var] : null;
	}
	public function COOKIE($var){
		return isset($this->_COOKIE[$var]) ? $this->_COOKIE[$var] : null;
	}
}

class MySQL {

	private $_connect = false;

	function __construct($server,$user,$password,$dbname,$locale="utf8"){
		$this->_connect = mysql_connect($server,$user,$password) or die("Can't connect to db. Invalid server/user/password.");
		mysql_select_db($dbname) or die("No access to db. Invalid db name.");
		mysql_query("set charset '$locale'");
		mysql_query("set character set '$locale'");
		mysql_query("set names '$locale'");
		mysql_query("SET SQL_BIG_SELECTS=1");
	}

	public function close(){
		mysql_close($this->_connect);
	}

	public function sendQuery($query){
		if ($this->getQ($query)){
			if (strpos($query,"insert") === 0){
				return mysql_insert_id();
			} else {
				return true;
			}
		}

		return false;
	}

	public function getQ($query){
		if ($result = mysql_query($query))
			return $result;
		else {
			$trace = debug_backtrace();
			$level = 0;
			if (in_array($trace[1]['function'], array('getCell', 'getRow', 'getColumn', 'getTable')))
				$level = 1;
			if (DOMAIN == "localhost"){
				$message =
					'<p><strong>MySQL error</strong> in file <strong>'.$trace[$level]['file'].'</strong>'.
					" at line <strong>" .$trace[$level]['line']."</strong>
					(function <strong>" . $trace[$level]['function'] ."</strong>):<br/>"
					."\n<span style='color:blue'>".mysql_error()."</span>\n\n<pre>$query</pre></p>";
				die($message);
			} else {
				die;
			}
		}
	}

	public function getCell($query,$row_name=0){
		$cell = FALSE;
		if ($result = $this->getQ($query) AND $row = mysql_fetch_array($result))
			$cell = $row[$row_name];
		return $cell;
	}

	public function getRow($query){
		$row = array();
		if ($result = $this->getQ($query))
			$row = mysql_fetch_assoc($result);
		return $row;
	}

	public function getColumn($query, $makehash = FALSE){
		$data = array();
		$result = $this->getQ($query);
		if (!$makehash){
			while ($row = mysql_fetch_row($result))
				$data[] = $row[0];
		}
		else{
			while ($row = mysql_fetch_array($result))
				$data[$row{0}] = $row[$makehash];
		}
		return $data;
	}

	public function getTable($query, $keycol = NULL){
		$data = array();
		$result = $this->getQ($query);
		if (is_null($keycol)){
			while ($row = mysql_fetch_assoc($result))
				$data[] = $row;
		}
		else{
			while ($row = mysql_fetch_assoc($result))
				$data[$row{$keycol}] = $row;
		}
		return $data;
	}
}

class User {

	private $_userId = 0;
	private $_userType = 'guest';
	private $_db;

	function __construct (){
		global $db;
		$this->_db = $db;

		// enter by session
		if (isset($_SESSION['userId']) && $_SESSION['userId'] != ''){

			$u = $this->_db->getRow("select `login`,`password` from `users` where `user_id` = '".$_SESSION['userId']."' limit 1");

			if (count($u) > 0) {
				$this->login($u['login'],$u['password'],false,true);
			}
		// enter by cookie
		} elseif (isset($_COOKIE['_auhash'])) {

			$hash = $_COOKIE['_auhash'];
			$r_user = $this->_db->getRow("select * from `remember_users` where `hash` = '$hash' limit 1");
			if ($r_user) {
				if ($r_user['before_time'] > time()){
					$u = $this->_db->getRow("select `type`,`login`,`password` from `users` where `user_id` = '".$r_user['user_id']."' limit 1");
					if (count($u) > 0)
						$this->login($u['login'],$u['password'],false,true);
				} else {
					setcookie("_auhash","",-1,"/",".".DOMAIN);
					$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$r_user[user_id]' limit 1");
				}
			}
		}
	}

	public function login($login,$password,$remember=false,$without_pass=false){
		$salt = $this->_db->getCell("select `salt` from `users` where `login` = '".$login."' limit 1");
		if (!$salt){
			return false;
		}

		$pass = !$without_pass ? md5(md5($password).$salt) : $pass = $password;

		$auth = $this->_db->getRow("select `user_id`,`type` from `users` where `login` = '".$login."' and `password` = '".$pass."' limit 1");

		if (!$auth) {
			return false;
		}

		if ($remember) {
			$before = time() + 1209600;
			$hash = md5($login.$before);
			$user_agent = $_SERVER['HTTP_USER_AGENT'];
			setcookie("_auhash",$hash,$before,"/",".".DOMAIN);
			// remember on 2 week
			$this->_db->sendQuery("insert into `remember_users` values (NULL,'$auth[user_id]','$hash','$before','$user_agent')");
		}

		$_SESSION['userId'] = $auth["user_id"];
		$this->_userId = $auth["user_id"];
		$this->_userType = $auth["type"];

		return true;
	}

	public function logout(){
		$hash = $_COOKIE['_auhash'] ? $_COOKIE['_auhash'] : 0;
		setcookie("_auhash","",-1,"/",".".DOMAIN);
		$user_id = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0;
		$this->_db->sendQuery("delete from `remember_users` where `user_id` = '$user_id' and `hash` = '$hash' limit 1");
		unset($_SESSION['userId']);
	}

	public function getUserId(){ return $this->_userId; }
	public function getUserType(){ return $this->_userType; }
	public function isGuest(){ return ($this->_userId == 0); }
	public function isUser(){ return ($this->_userType == 'user'); }
	public function isAdmin(){ return ($this->_userType == 'administrator'); }
}

class UV {

	static function readInt($var,$min=0,$max=4294967296) { return filter_var($var,FILTER_VALIDATE_INT); }
	static function readBool($var) { return filter_var($var,FILTER_VALIDATE_BOOLEAN); }
	static function readMQ($var) { return filter_var($var,FILTER_SANITIZE_MAGIC_QUOTES); }
}

?>